package com.ifreeee.practice.pc.bilibili;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

public class JsonPropUtils {

    private static final String json = "";

    private static final String sep = "\n";

    private static final String propName = "bvid";

    public static String getJsonObj (String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }

        JSONObject jsonObject = JSON.parseObject(json);
        if (jsonObject == null) {
            return null;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (data == null) {
            return null;
        }
        String medias = data.getString("medias");
        if (StringUtils.isBlank(medias)) {
            return null;
        }
        return medias;
    }

    public static List<String> getJsonProp (String json, String propName) {
        List<JSONObject> jsonObjects = JSON.parseArray(json, JSONObject.class);
        return jsonObjects.stream()
                .filter(Objects::nonNull)
                .map(jsonObject -> jsonObject.get(propName))
                .filter(Objects::nonNull)
                .map(Objects::toString)
                .collect(Collectors.toList());
    }

    public static List<String> getJsonProp (List<String> jsonList, String propName) {
        if (CollectionUtils.isEmpty(jsonList)) {
            return null;
        }
        List<String> res = new ArrayList<>();
        for (String s : jsonList) {
            res.addAll(getJsonProp(s, propName));
        }
        return res;
    }

    public static void print (List<String> props, String sep) {

        if (CollectionUtils.isEmpty(props)) {
            System.out.println(Collections.emptyList());
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (String prop : props) {
            stringBuilder.append(prop);
            stringBuilder.append(sep);
        }

        System.out.println(stringBuilder);

    }

    public static void main(String[] args) {
        List<String> jsonProp = getJsonProp(json, propName);
        print(jsonProp, sep);
    }



}
